package com.rbac.service.impl;

import com.rbac.dto.PermissionQueryDTO;
import com.rbac.entity.SysPermission;
import com.rbac.mapper.PermissionMapper;
import com.rbac.service.PermissionService;
import com.rbac.vo.PermissionVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    @Override
    public SysPermission getPermissionByPermissionCode(String permissionCode) {
        return permissionMapper.selectByPermissionCode(permissionCode);
    }
    
    @Override
    public SysPermission getPermissionById(Long id) {
        return permissionMapper.selectById(id);
    }
    
    @Override
    public PageInfo<PermissionVO> getPermissionList(PermissionQueryDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPageNum(), queryDTO.getPageSize());
        
        List<PermissionVO> permissionList = permissionMapper.selectPermissionList(queryDTO);
        
        return new PageInfo<>(permissionList);
    }
    
    @Override
    public List<SysPermission> getAllPermissions() {
        return permissionMapper.selectAllPermissions();
    }
    
    @Override
    @Transactional
    public boolean addPermission(SysPermission permission) {
        // 检查权限编码是否已存在
        SysPermission existPermission = permissionMapper.selectByPermissionCode(permission.getPermissionCode());
        if (existPermission != null) {
            return false;
        }
        
        permission.setStatus(1); // 默认启用
        permission.setVisible(1); // 默认可见
        permission.setSortOrder(0); // 默认排序
        permission.setCreateTime(LocalDateTime.now());
        
        return permissionMapper.insert(permission) > 0;
    }
    
    @Override
    @Transactional
    public boolean updatePermission(SysPermission permission) {
        permission.setUpdateTime(LocalDateTime.now());
        return permissionMapper.update(permission) > 0;
    }
    
    @Override
    @Transactional
    public boolean deletePermission(Long id) {
        return permissionMapper.deleteById(id) > 0;
    }
    
    @Override
    @Transactional
    public boolean updatePermissionStatus(Long id, Integer status) {
        SysPermission permission = new SysPermission();
        permission.setId(id);
        permission.setStatus(status);
        permission.setUpdateTime(LocalDateTime.now());
        return permissionMapper.update(permission) > 0;
    }
} 